package tech.eyao.hs60x.worker;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanInstantiationException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import com.google.zxing.WriterException;
import tech.eyao.hs60x.common.CommonConstants;
import tech.eyao.hs60x.push.CodeImageFactory;
import tech.eyao.hs60x.utils.Base64Utils;

public class UserImageWorker extends AbstractImageWorker {

	private static final Logger	logger	= LoggerFactory.getLogger(UserImageWorker.class);
	private final Long			userId;

	public UserImageWorker(long userId) {
		this.userId = userId;
	}

	@Override
	public void doRun() {
		logger.info("[UserImageWorker doRun] " + userId);
		String imageName = Base64Utils.encode(String.valueOf(userId).getBytes()) + CommonConstants.IMAGE_FORMAT;
		// 计算文件路径
		String pathValue = CommonConstants.IMG_URI + CommonConstants.SLASH + (userId % CommonConstants.FILESIZE)
				+ CommonConstants.SLASH;
		Path path = Paths.get(pathValue);
		if (!Files.exists(path)) {
			try {
				Files.createDirectory(path);
			} catch (IOException e) {
				logger.error("[UserImageWorker doRun ]" + path.getFileName(), e);
			}
		}

		// 生成图片
		String logUri = "e://temp/20171014125015.jpg";
		String content = "http://www.baidu.com";
		int[] size = new int[] { 430, 430 };
		try {
			if (!Files.exists(Paths.get(pathValue + imageName))) {
				BeanUtils.instantiate(CodeImageFactory.class).creatImage(content, "jpg", pathValue + imageName, logUri,
						size);
			}
		} catch (BeanInstantiationException | IOException | WriterException e) {
			e.printStackTrace();
		}
		// 保存记录
	}
}
